//
//  CZPayViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/8.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZPayViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "CZMineViewController.h"

@interface CZPayViewController ()
@property (weak, nonatomic) IBOutlet UIButton *wechatPayBtn;
@property (weak, nonatomic) IBOutlet UIButton *alipayBtn;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;

@property (nonatomic, copy) NSString *orderID;
@property (nonatomic, copy) NSString *orderNumber;


@end

@implementation CZPayViewController
- (void)awakeFromNib {
    [super awakeFromNib];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付";
    [(UIView*)[self.navigationController.navigationBar.subviews objectAtIndex:0] setAlpha:1.f];
    [self getPriceData];
//    self.view.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    // Do any additional setup after loading the view from its nib.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.alpha = 1;

    [(UIView*)[self.navigationController.navigationBar.subviews objectAtIndex:0] setAlpha:1.f];
}
- (IBAction)wechatPayAction:(id)sender {
    UIButton *wechatPayBtn = (UIButton *)sender;
    wechatPayBtn.selected = !wechatPayBtn.selected;
    if (_alipayBtn.selected) {
        _alipayBtn.selected = NO;
    }
}
- (IBAction)alipayAction:(id)sender {
    UIButton *alipayBtn = (UIButton *)sender;
    alipayBtn.selected = !alipayBtn.selected;
    if (_wechatPayBtn.selected) {
        _wechatPayBtn.selected = NO;
    }
}
- (IBAction)payAction:(UIButton *)sender {
    if (!self.alipayBtn.selected && !self.wechatPayBtn.selected) {
        [SVProgressHUD showErrorWithStatus:@"请选择支付方式"];
        return;
    }
    if (self.alipayBtn.selected) {
        // alipay
        [self getOrderWithPayMethod:@"alipay"];
//        [Pingpp crea];
    } else {
        //wechatPay
        [self getOrderWithPayMethod:@"wx"];
    }
}

- (void)getOrderWithPayMethod:(NSString *)payMethod {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/order/pay-order",APP_HOST];
    [SVProgressHUD showWithStatus:@"生成订单中..."];
    
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"order_id" : self.orderID, @"pay_channel" : payMethod} success:^(NSDictionary *response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            [SVProgressHUD dismiss];
            NSData *data = [NSJSONSerialization dataWithJSONObject:response[@"result"] options:(NSJSONWritingPrettyPrinted) error:nil];

            NSString* charge = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            DLog(@"%@", charge);
            [Pingpp createPayment:charge appURLScheme:@"pay" withCompletion:^(NSString *result, PingppError *error) {
                if ([result isEqualToString:@"success"]) {
                    // 支付成功
                    DLog(@"支付成功");
                    [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                    CZMineViewController *mineVC = self.navigationController.childViewControllers[0];
                    [mineVC getUserData
                     ];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                } else {
                    // 支付失败或取消
                    NSLog(@"Error: code=%lu msg=%@", (unsigned long)error.code, [error getMsg]);
                }
            }];
            

        } else {
            [SVProgressHUD showErrorWithStatus:response[@"message"]];
            
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

- (void)getPriceData {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/order/create",APP_HOST];
    NSDictionary *parma;

    if (self.inviteId) {
        parma = @{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"product_id" : self.productId, @"invite_id" : self.inviteId};
    } else {
        parma = @{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"product_id" : self.productId};
    }
    
    [GCZAFNetWorking POST:urlString params:parma success:^(NSDictionary *response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            self.priceLabel.text = [NSString stringWithFormat:@"%@", response[@"result"][@"order_price"]];
            self.orderID = response[@"result"][@"order_id"];
            self.orderNumber = response[@"result"][@"order_no"];
        } else {
            [SVProgressHUD showErrorWithStatus:response[@"message"]];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
